import jwt
from functools import wraps
from flask import request, jsonify, g, current_app
from datetime import datetime, timedelta
from app.utils.logger import get_logger
import os

logger = get_logger(__name__)

JWT_BYPASS_ENABLED = True  

def generate_token(user_id, expires_in=86400):
    """生成JWT令牌"""
    payload = {
        'sub': user_id,
        'exp': datetime.utcnow() + timedelta(seconds=expires_in)
    }
    
    token = jwt.encode(
        payload=payload,
        key=current_app.config['SECRET_KEY'],
        algorithm="HS256"
    )
    
    # 处理Python版本差异
    if isinstance(token, bytes):
        token = token.decode('utf-8')
        
    return token

def auth_required(f):
    """需要授权的装饰器式"""
    @wraps(f)
    def decorated(*args, **kwargs):
 
        if JWT_BYPASS_ENABLED:
            logger.warning("使用用户身份 (ID=1)")
            g.user_id = 1  
            return f(*args, **kwargs)
        
        auth_header = request.headers.get('Authorization')
        if not auth_header:
            return jsonify({
                "code": 401,
                "message": "缺少Authorization头"
            }), 401
        
        try:
            if not auth_header.startswith('Bearer '):
                return jsonify({
                    "code": 401,
                    "message": "无效的Authorization格式"
                }), 401
                
            token = auth_header.split(' ')[1]
            
            payload = jwt.decode(
                token,
                current_app.config['SECRET_KEY'],
                algorithms=["HS256"]
            )
            
            g.user_id = payload['sub']
            return f(*args, **kwargs)
            
        except jwt.ExpiredSignatureError:
            return jsonify({
                "code": 401,
                "message": "token已过期"
            }), 401
        except jwt.InvalidTokenError:
            return jsonify({
                "code": 401,
                "message": "无效token"
            }), 401
        except Exception as e:
            logger.error(f"认证异常: {str(e)}")
            return jsonify({
                "code": 500,
                "message": "认证过程中发生错误"
            }), 500
            
    return decorated